clear all;close all;clc;

datastr = importdata("iris.data");

for i = 1:length(datastr)
    str = strrep(cell2mat(datastr(i)), ',', ' '); % 移除逗号
    nums(i,:) = str2double(regexp(str, '[-+]?\d*\.?\d', 'match')); % 提取带有小数点的数字
end

X = nums(:,3:4);
plot(X(:,1),X(:,2),".");
IDX = dbscan(X,0.5,10);
gscatter(X(:,1),X(:,2),IDX);
for i = 1:length(X)
    dis(i) = point_distance(X(1,:),X(i,:));
end
plot(dis);

function [dis] = point_distance(point1,point2)
    dis = ((point1(1) - point2(1))^2 + (point1(2) - point2(2))^2)^0.5;
end

function [index] = my_dbscan(data,expilon,minpts)
    index = zeros(1,length(data));
    core_record = zeros(1,length(data));
    core_num = 0;
    obj_num = zeros(1,length(data));
    obj_record = zeros(length(data),length(data));
    labnum = 0;
    core_tag = zeros(1,length(data));
    for i = 1:length(data)
        for j = i + 1:length(data)
            dis = point_distance(data(i,:),data(j,:));
            %找到距离小于expilon的点并记录点序号及符合条件点的数目
            if(dis < expilon)
                obj_num(i) = obj_num(i);
                obj_record(i,obj_num(i)) = j;
            end
        end
        %如果符合条件点的数量大于minpts，则记录该点位核心点
        if(obj_num(i) > minpts)
            core_num = core_num + 1;
            core_record(core_num) = i;
        end
    end

    %寻找密度可达
    for i = 1:core_num
        if(core_tag(i) == 0)
            labnum = labnum + 1;
            core_tag(i) = labnum;
            %寻找密度直达
            for j = i+1:core_num
                if(point_distance(data(:,core_record(i)),data(:,core_record(j))) < expilon)
                    core_tag(j) = labnum;
                end
            end
        end
    end
    
    %分类非核心点
end